<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="利润日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="分类类型" prop="categoryType">
        <el-select v-model="queryParams.categoryType" placeholder="请选择分类类型" clearable style="width: 150px">
          <el-option label="收入" :value="1"></el-option>
          <el-option label="支出" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择项目分类" clearable style="width: 180px">
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="relatedOrderNo">
        <el-select
          v-model="queryParams.relatedOrderNo"
          placeholder="请选择订单号"
          clearable
          filterable
          style="width: 200px"
          @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in orderOptions"
            :key="item.id"
            :label="item.orderNo"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['operations:profitDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operations:profitDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operations:profitDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['operations:profitDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="利润日期" align="center" prop="profitDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.profitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目分类" align="center" prop="categoryName" width="120" />
      <el-table-column label="分类类型" align="center" prop="categoryType" width="90">
        <template slot-scope="scope">
          <el-tag :type="scope.row.categoryType === 1 ? 'success' : 'danger'" size="mini">
            {{ scope.row.categoryType === 1 ? '收入' : '支出' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" width="120">
        <template slot-scope="scope">
          <span :class="scope.row.categoryType === 1 ? 'income-text' : 'expense-text'">
            ¥{{ formatMoney(scope.row.amount) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="关联订单号" align="center" prop="relatedOrderNo" width="150">
        <template slot-scope="scope">
          <span>{{ formatOrderNo(scope.row.relatedOrderNo) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细说明" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['operations:profitDetail:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['operations:profitDetail:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="利润日期" prop="profitDate">
              <el-date-picker
                v-model="form.profitDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择项目分类" style="width: 100%" @change="handleCategoryChange">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="`【${item.categoryType === 1 ? '收入' : '支出'}】${item.categoryName}`"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="金额" prop="amount">
              <el-input-number v-model="form.amount" :precision="2" :min="0" :max="99999999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联订单号" prop="relatedOrderNo">
              <el-select v-model="form.relatedOrderNo" placeholder="请选择关联订单号（选填）" clearable filterable style="width: 100%">
                <el-option
                  v-for="item in orderOptions"
                  :key="item.id"
                  :label="item.orderNo"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细说明" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入详细说明" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProfitDetail, getProfitDetail, addProfitDetail, updateProfitDetail, delProfitDetail } from "@/api/operations/profitDetail"
import { listProfitCategory } from "@/api/operations/profitCategory"
import { selectOrderList, getOrders } from "@/api/dashboard/orders"
import { calculateDailySalary } from "@/api/system/salary"

export default {
  name: "ProfitDetail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 明细列表
      detailList: [],
      // 分类选项
      categoryOptions: [],
      // 订单选项
      orderOptions: [],
      // 订单号缓存（用于列表显示）
      orderNoCache: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        categoryType: null,
        relatedOrderNo: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        profitDate: [
          { required: true, message: "利润日期不能为空", trigger: "change" }
        ],
        categoryId: [
          { required: true, message: "项目分类不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "金额不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryList()
    this.getOrderList()
  },
  methods: {
    /** 查询明细列表 */
    getList() {
      this.loading = true
      const params = this.addDateRange(this.queryParams, this.dateRange, 'ProfitDate')
      listProfitDetail(params).then(response => {
        this.detailList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询分类列表 */
    getCategoryList() {
      listProfitCategory({ status: 1 }).then(response => {
        this.categoryOptions = response.rows
      })
    },
    /** 查询订单列表 */
    getOrderList() {
      selectOrderList().then(response => {
        // /list 接口返回 {rows: [...], total: ...} 格式
        const orders = response.rows || []
        // 只提取 id 和 orderNo 字段
        this.orderOptions = orders.map(order => ({
          id: order.id,
          orderNo: order.orderNo
        }))
        // 缓存订单号映射
        this.orderOptions.forEach(order => {
          this.orderNoCache[order.id] = order.orderNo
        })
      })
    },
    /** 格式化订单号显示 */
    formatOrderNo(orderId) {
      if (!orderId) return '-'
      // 先从缓存中获取
      if (this.orderNoCache[orderId]) {
        return this.orderNoCache[orderId]
      }
      // 如果缓存中没有，异步获取并缓存
      getOrders(orderId).then(response => {
        if (response.data && response.data.orderNo) {
          this.$set(this.orderNoCache, orderId, response.data.orderNo)
        }
      }).catch(() => {
        this.$set(this.orderNoCache, orderId, '未知')
      })
      return '加载中...'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        profitDate: null,
        categoryId: null,
        amount: null,
        relatedOrderNo: null,
        description: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加利润明细"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getProfitDetail(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改利润明细"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProfitDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProfitDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(',')
      this.$modal.confirm('是否确认删除选中的利润明细数据？').then(function() {
        return delProfitDetail(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('operations/profitDetail/export', {
        ...this.queryParams
      }, `利润明细_${new Date().getTime()}.xlsx`)
    },
    /** 格式化金额 */
    formatMoney(val) {
      if (val == null || val === '') return '0.00'
      return parseFloat(val).toFixed(2)
    },
    /** 项目分类改变时触发 */
    handleCategoryChange(categoryId) {
      // 查找选中的分类
      const selectedCategory = this.categoryOptions.find(cat => cat.id === categoryId)
      
      // 判断是否是"员工日工资"分类
      if (selectedCategory && selectedCategory.categoryCode === 'employee_daily_salary') {
        this.calculateEmployeeDailySalary()
      }
    },
    /** 计算员工日工资 */
    calculateEmployeeDailySalary() {
      // 获取表单中的利润日期
      const profitDate = this.form.profitDate
      let yearMonth = null
      
      if (profitDate) {
        // 从日期中提取年月 (YYYY-MM)
        yearMonth = profitDate.substring(0, 7)
      }
      
      // 调用API计算日工资
      calculateDailySalary(yearMonth).then(response => {
        if (response.code === 200 && response.data) {
          const dailySalary = response.data.dailySalary
          this.form.amount = parseFloat(dailySalary)
          
          // 提示用户
          const workingDays = response.data.workingDays
          const totalDays = response.data.totalDays
          this.$modal.msgSuccess(
            `已自动计算${response.data.yearMonth}月员工日工资：¥${dailySalary}\n` +
            `本月共${totalDays}天，工作日${workingDays}天（排除周日）`
          )
        }
      }).catch(error => {
        this.$modal.msgError('计算员工日工资失败：' + (error.msg || '未知错误'))
      })
    }
  }
}
</script>

<style scoped>
.income-text {
  color: #67C23A;
  font-weight: bold;
}

.expense-text {
  color: #F56C6C;
  font-weight: bold;
}
</style>

